package com.efounder.common.floatwindow;

import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.IBinder;
import android.provider.Settings;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;

import com.efounder.constant.EnvironmentVariable;
import com.efounder.mobilecomps.R;
import com.efounder.util.AppContext;
import com.efounder.util.EnvSupportManager;
import com.efounder.util.ToastUtil;
import com.efounder.utils.EasyPermissionUtils;
import com.utilcode.util.ActivityUtils;
import com.utilcode.util.AppUtils;
import com.utilcode.util.ReflectUtils;
import com.utilcode.util.ServiceUtils;
import com.utilcode.util.Utils;

/**
 * 悬浮窗服务
 *
 * @autor yqs
 * @date 2019/5/13 15:17
 **/
public class FloatWindowService extends Service {

    private static final String TAG = "FloatWindowService";
    //应用是否在前台
    private boolean isOnForeground = true;
    private IFloatWindow floatWindowManager;
    //请求悬浮窗权限的code
    public static final int REQUEST_CODE_PERMISSON_OVERLAY = 2019;


    /**
     * 判断并请求悬浮窗权限
     *
     * @param activity
     * @param isOnActovityResult 是否是on avtivity result返回之后回调
     * @return
     */
    public static boolean checkOverLayPermission(final Activity activity, boolean isOnActovityResult) {
        //是否支持悬浮窗服务
        boolean isSupportFloatService = EnvSupportManager.isSupportFloatWindow();
        if (!isSupportFloatService) {
            return false;
        }
        if (EasyPermissionUtils.checkOverLayPermission()) {
            return true;
        }
        if (EnvironmentVariable.getProperty("notTipOverLay", "0").equals("1")) {
            //如果不再提示获取悬浮窗权限
            return false;
        }

        new AlertDialog.Builder(ActivityUtils.getTopActivity()).setTitle(R.string.common_text_hint)
                .setMessage(R.string.permission_overlay)
                .setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        try {
//                            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
//                            intent.setData(Uri.parse(AppUtils.getAppPackageName()));
                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                                    .setData(Uri.fromParts("package", AppUtils.getAppPackageName(), null));
                            activity.startActivityForResult(intent, REQUEST_CODE_PERMISSON_OVERLAY);
                        } catch (Exception e) {
                            ToastUtil.showToast(AppContext.getInstance(), R.string.wechatview_access_fail);
                        }
                    }
                })
                .setNegativeButton(R.string.common_text_cancel, null)
                .setNeutralButton(R.string.common_text_not_tips, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        EnvironmentVariable.setProperty("notTipOverLay", "1");
                    }
                }).create().show();

        return false;

    }

    /**
     * 启动悬浮窗服务
     *
     * @param context
     */
    public static void startFloatService(Context context) {
        //服务是否正在运行
        boolean isServiceRuning = ServiceUtils.isServiceRunning(FloatWindowService.class.getCanonicalName());
        //是否支持悬浮窗服务
        boolean isSupportFloatService = EnvSupportManager.isSupportFloatWindow();
        if (isSupportFloatService && !isServiceRuning) {
            Intent intent = new Intent(context, FloatWindowService.class);
            context.startService(intent);
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    @Override
    public void onCreate() {
        super.onCreate();
        registerAppStatus();
        floatWindowManager = getIFloatWindow();
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        AppUtils.unregisterAppStatusChangedListener(this);
        if (floatWindowManager != null && floatWindowManager.isShowing()) {
            floatWindowManager.hide();
        }
    }

    /**
     * 注册服务前后台状态监听
     */
    private void registerAppStatus() {
        AppUtils.registerAppStatusChangedListener(this, new Utils.OnAppStatusChangedListener() {
            @Override
            public void onForeground() {
                isOnForeground = true;
                if (floatWindowManager != null) {
                    floatWindowManager.show();
                }
            }

            @Override
            public void onBackground() {
                isOnForeground = false;
                if (floatWindowManager != null) {
                    floatWindowManager.hide();
                }
            }
        });
    }


    private IFloatWindow getIFloatWindow() {
        String className = getResources().getString(R.string.default_app_float_window_class);
        String floatViewClassName = getResources().getString(R.string.default_app_float_window_view_class);

        try {
            ReflectUtils reflectUtils = ReflectUtils.reflect(className);
            IFloatView floatView = ReflectUtils.reflect(floatViewClassName).newInstance(ActivityUtils.getTopActivity()).get();
            IFloatWindow iFloatWindow = reflectUtils.newInstance(floatView).get();
            return iFloatWindow;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }
}
